﻿namespace DistrRTgen
{
    using System;
    using System.Collections.Generic;
    using System.Xml;
    using System.Xml.Schema;
    using System.Xml.Serialization;

    [XmlRoot("Settings")]
    internal class SerializableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, IXmlSerializable
    {
        public XmlSchema GetSchema()
        {
            return null;
        }

        public void ReadXml(XmlReader reader)
        {
            XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));
            XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));
            bool wasEmpty = reader.IsEmptyElement;
            reader.Read();
            if (!wasEmpty)
            {
                try
                {
                    while (reader.NodeType != XmlNodeType.None)
                    {
                        reader.ReadStartElement("item");
                        reader.ReadStartElement("key");
                        TKey key = (TKey) keySerializer.Deserialize(reader);
                        reader.ReadEndElement();
                        reader.ReadStartElement("value");
                        TValue value = (TValue) valueSerializer.Deserialize(reader);
                        reader.ReadEndElement();
                        base.Add(key, value);
                        reader.ReadEndElement();
                        reader.MoveToContent();
                    }
                }
                catch (InvalidOperationException)
                {
                }
            }
        }

        public void WriteXml(XmlWriter writer)
        {
            XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));
            XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));
            foreach (TKey key in base.Keys)
            {
                writer.WriteStartElement("item");
                writer.WriteStartElement("key");
                keySerializer.Serialize(writer, key);
                writer.WriteEndElement();
                writer.WriteStartElement("value");
                TValue value = base[key];
                valueSerializer.Serialize(writer, value);
                writer.WriteEndElement();
                writer.WriteEndElement();
            }
        }
    }
}

